/*
 * @Author: Igris
 * @Date: 2024-06-14 16:14:53
 * @LastEditors: chenw chenw@qq.com
 * @LastEditTime: 2024-06-27 13:54:00
 * @Description: 表格增删改查 hooks
 */

import { ElMessageBox, ElMessage } from 'element-plus'

export const useOperaTable = <
  FI extends Record<string, unknown>,
  SI extends Record<string, unknown>
>(
  formDataInput: FI = {} as FI,
  searchInput: SI = {} as SI,
  url: string
) => {
  const tableData = ref([])
  const total = ref(0)
  const page = ref(1)
  const pageSize = ref(20)

  const tip = ref(0) // 0 新增  1 编辑
  const dialogIsShow = ref(false)
  const formParams = ref(formDataInput) as Ref<FI>
  const editFormParams = ref<Record<string, unknown>>({})
  const searchKeys = ref(searchInput) as Ref<SI>

  const getTableData = <QT extends Record<string, any>>(query = {} as QT) => {
    $ajax
      .get(url, {
        ...query,
        page: page.value
        // pageSize: pageSize.value
      })
      .then(res => {
        if ('results' in res.data) {
          tableData.value = res.data.results
          total.value = res.data.count
        } else {
          tableData.value = res.data
          total.value = res.count
        }
      })
  }

  const handleQuery = () => {
    page.value = 1
    getTableData(searchKeys.value)
  }

  const handleSizeChange = (size: number) => {
    pageSize.value = size
    getTableData(searchKeys.value)
  }

  const handlePageChange = (c_page: number) => {
    page.value = c_page
    getTableData(searchKeys.value)
  }

  const handleCreate = () => {
    tip.value = 0
    dialogIsShow.value = true
  }
  const handleConfirmCreate = (
    api: string,
    method: keyof typeof $ajax = 'post'
  ) => {
    const params = Object.assign({}, formParams.value)
    // 处理密码
    // if (Reflect.has(params, 'pwd_hash')) {
    //   Reflect.set(
    //     params,
    //     'pwd_hash',
    //     md5(Reflect.get(params, 'pwd_hash') as string)
    //   )
    // }
    console.log(params)

    $ajax[method](api, {
      ...params
    })
      .then(() => {
        ElMessage({
          type: 'success',
          message: `${tip.value ? '编辑' : '新增'}成功`
        })
        getTableData(searchKeys.value)
        dialogIsShow.value = false
      })
      .catch(() => {
        ElMessage({
          type: 'error',
          message: `${tip.value ? '编辑' : '新增'}失败`
        })
        dialogIsShow.value = false
      })
  }

  const handleEdit = <ET extends Record<string, unknown>>(row: ET) => {
    dialogIsShow.value = true
    tip.value = 1

    editFormParams.value = Object.assign({}, row)
  }

  watch(editFormParams, (n, v) => {
    formParams.value = n as FI
  })

  const handleDel = <DT>(
    api: string,
    delParams: DT,
    method: keyof typeof $ajax = 'post'
  ) => {
    ElMessageBox.confirm('此操作将会永久删除这条信息. 是否继续?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      $ajax[method](api, {
        ...delParams
      })
        .then(() => {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getTableData(searchKeys.value)
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: '删除失败'
          })
        })
    })
  }

  const handleClose = () => {
    // 表单置空
    Object.keys(formParams.value).forEach(key => {
      Reflect.set(formParams.value, key, '')
    })
  }

  onMounted(() => {
    getTableData()
  })

  return {
    tableData,
    total,
    page,
    pageSize,
    dialogIsShow,
    tip,
    formParams,
    editFormParams,
    searchKeys,

    getTableData,

    handleQuery,
    handleSizeChange,
    handlePageChange,

    handleEdit,

    handleDel,
    handleCreate,
    handleConfirmCreate,

    handleClose
  }
}
